package com.chey.filter;

import com.chey.util.RedisCache;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author JanYao
 * @version 0.1
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        //为空的话直接放行
        if (StringUtils.isEmpty(token) || "".equals(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        String key = "login:token:"+token;
        List<String> cacheList = redisCache.getCacheList(key);

        if (cacheList.isEmpty()) {
            throw  new RuntimeException("用户未登录,请先登录");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String url :cacheList) {
                grantedAuthorities.add(new SimpleGrantedAuthority(url));
        }


        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(null,null,grantedAuthorities);
        System.out.println("authenticationToken:"+authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}
